//
//  SEGEditAdressViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/9.
//

#import "SEGEditAdressViewModel.h"

@interface SEGEditAdressViewModel ()

@property (nonatomic, strong) SEGAddressModel *addressModel;
@property (nonatomic, assign) EditAdressShowType showType;

@end

@implementation SEGEditAdressViewModel

- (instancetype)initWithShowType:(EditAdressShowType)showType addressModel:(SEGAddressModel *)model {
    self = [super init];
    if (self) {
        self.showType = showType;
        self.addressModel = model;
        [self seg_createDeleteAddressCommand];
        [self seg_createUpdateAddressCommand];
    }
    return self;
}
- (void)seg_createDeleteAddressCommand {
    @weakify(self);
    self.deleteAddressCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.myManager requestDeleteAddressByid:self.addressModel.id Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    [subscriber sendNext:errorMessage];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }];
}
- (void)seg_createUpdateAddressCommand {
    @weakify(self);
    self.updateAddressCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSNumber *bo) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            NSString *str0 = [NSString string];
            NSString *str1 = [NSString string];
            NSString *str2 = [NSString string];
          
            NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
            if (0 < self.dataSourceArr.count) {
                str0 = [self.dataSourceArr[0] valueForKey:@"value"];
                str0 = [str0 stringByTrimmingCharactersInSet:set];
            }
            if (1 < self.dataSourceArr.count) {
                str1 = [self.dataSourceArr[1] valueForKey:@"value"];
                str1 = [str1 stringByTrimmingCharactersInSet:set];
            }
            if (2 < self.dataSourceArr.count) {
                str2 = [self.dataSourceArr[2] valueForKey:@"value"];
                str2 = [str2 stringByTrimmingCharactersInSet:set];
            }
            if ([str0 length] <= 0) {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:@"收货人不能为空！"}];
                [subscriber sendError:error];
                return nil;
            }
            if ([str1 length] != 11) {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:kPhoneError}];
                [subscriber sendError:error];
                return nil;
            }
            if ([str2 length] <= 0) {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:@"详细地址不能为空！"}];
                [subscriber sendError:error];
                return nil;
            }

            // 新建配送地址
            if (self.showType == EditAdressShowType_ADD || self.showType == EditAdressShowType_ADD_Order) {
                [self.myManager requestNewAddAddressByaddress:str2 contactName:str0 contactPhone:str1 isDefault:bo.boolValue ? @"1" : @"0" Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        if (bo.boolValue) { // 更新默认配送地址
                            [SEGProfileManager sharedManager].profile.addressId = codeType;
                            [SEGProfileManager sharedManager].profile.defaultAddress = str2;
                        }
                        
                        if (self.showType == EditAdressShowType_ADD_Order) {
                            SEGAddressModel *data = [[SEGAddressModel alloc] init];
                            data.id = codeType;
                            data.userAddress = str2;
                            data.defaultType = bo.boolValue ? @"1" : @"0";
                            data.contactName = str0;
                            data.contactPhone = str1;
                            data.isDefault = bo.boolValue ? @"1" : @"0";
                    
                            [subscriber sendNext:RACTuplePack(data, errorMessage)];
                            [subscriber sendCompleted];
                        } else {
                            [subscriber sendNext:RACTuplePack([SEGAddressModel new], errorMessage)];
                            [subscriber sendCompleted];
                       }
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
            }
            
           // 修改配送地址
           if (self.showType == EditAdressShowType_EDITE || self.showType == EditAdressShowType_EDITE_Order) {
                [self.myManager requestUpdateAddressByid:self.addressModel.id address:str2 contactName:str0 contactPhone:str1 isDefault:bo.boolValue ? @"1" : @"0" Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        if (bo.boolValue) { // 更新默认配送地址
                            [SEGProfileManager sharedManager].profile.addressId = self.addressModel.id;
                            [SEGProfileManager sharedManager].profile.defaultAddress = str2;
                        }
                        
                        if (self.showType == EditAdressShowType_EDITE_Order) {
                            SEGAddressModel *data = [[SEGAddressModel alloc] init];
                            data.id = self.addressModel.id;
                            data.userAddress = str2;
                            data.defaultType = bo.boolValue ? @"1" : @"0";
                            data.contactName = str0;
                            data.contactPhone = str1;
                            data.isDefault = bo.boolValue ? @"1" : @"0";

                            [subscriber sendNext:RACTuplePack(data, errorMessage)];
                            [subscriber sendCompleted];
                        } else {
                            [subscriber sendNext:RACTuplePack([SEGAddressModel new], errorMessage)];
                            [subscriber sendCompleted];
                        }
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
            }
            return nil;
        }];
    }];
}

#pragma mark - Getter
- (SEGMyManager *)myManager {
    if (!_myManager) _myManager = [[SEGMyManager alloc] init];
    return _myManager;
}
- (NSArray *)dataSourceArr {
    if (!_dataSourceArr) {
        if (self.showType == EditAdressShowType_EDITE || self.showType == EditAdressShowType_ADD) {
            NSMutableArray *arrM = [NSMutableArray arrayWithArray:[self segEditAddressOrder]];
            for (int i = 0; i < arrM.count; i++) {
                NSMutableDictionary* dic = arrM[i];
                switch (i) {
                    case 0: {
                        [dic setValue:(self.showType == EditAdressShowType_ADD) ? @"" : self.addressModel.contactName forKey:@"value"];
                    } break;
                    case 1: {
                        [dic setValue:(self.showType == EditAdressShowType_ADD) ? @"" : self.addressModel.contactPhone forKey:@"value"];
                    } break;
                    case 2: {
                        [dic setValue:(self.showType == EditAdressShowType_ADD) ? @"" : self.addressModel.userAddress forKey:@"value"];
                    } break;
                        
                    default:
                        break;
                }
            }
            _dataSourceArr = [NSArray arrayWithArray:arrM];
        } else {
            NSMutableArray *arrM = [NSMutableArray arrayWithArray:[self segEditAddressOrder]];
            for (int i = 0; i < arrM.count; i++) {
                NSMutableDictionary* dic = arrM[i];
                switch (i) {
                    case 0: {
                        [dic setValue:(self.showType == EditAdressShowType_ADD_Order) ? @"" : self.addressModel.contactName forKey:@"value"];
                    } break;
                    case 1: {
                        [dic setValue:(self.showType == EditAdressShowType_ADD_Order) ? @"" : self.addressModel.contactPhone forKey:@"value"];
                    } break;
                    case 2: {
                        [dic setValue:(self.showType == EditAdressShowType_ADD_Order) ? @"" : self.addressModel.userAddress forKey:@"value"];
                    } break;
                        
                    default:
                        break;
                }
            }
            _dataSourceArr = [NSArray arrayWithArray:arrM];
        }
    }
    return _dataSourceArr;
}
-(NSMutableArray *)segEditAddressOrder {
    NSMutableArray *arrM = [NSMutableArray array];
    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"1",@"name":@"收货人",@"value":@""}]];
    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"2",@"name":@"手机号码",@"value":@""}]];
    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"3",@"name":@"详细地址",@"value":@""}]];
    [arrM addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"key":@"4",@"name":@"默认地址",@"value":@"注：每次下单时会使用该地址"}]];
    return arrM;
}

@end
